package com.wiseMen.weixin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wiseMen.platform.utils.RequestUtils;
import com.wiseMen.weixin.user.WxUserEntity;
import com.wiseMen.weixin.user.WxUserService;
import com.wiseMen.weixin.utils.Constant;
import com.wiseMen.weixin.utils.SessionUtils;

/**
 * 中小企业微信应用
 * @author linyubang
 * @email bangyulin@qq.com
 * @date 2016年11月13日
 */
@Controller
public class WeixinAction {
	
	@Autowired
	private WxUserService wxUserService;
	
	@RequestMapping("/weixin/index")
	public String Index(){
		return "weixin/index";
	}
	
	//注册
	@RequestMapping("/weixin/echostr")
	public String echostr(){
		  String echostr = RequestUtils.getServletRequest().getParameter("echostr");
		  return echostr;
	}
	
	@RequestMapping("/weixin/service")
	public String service(){
		String echostr = RequestUtils.getServletRequest().getParameter("echostr");
		if(StringUtils.isNotEmpty(echostr)){
			try {
				this.write(echostr, RequestUtils.getServletResponse());
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}else{
			WxUserEntity user = SessionUtils.getUser();
			if(user==null){
				String openId = SessionUtils.getOpenId();
				if(StringUtils.isBlank(openId)){
					openId = SessionUtils.refurbishOpenId(RequestUtils.getServletRequest().getParameter("code"));
				}
				if(StringUtils.isNotBlank(openId) && wxUserService.isRegister(openId)){
					user = wxUserService.findById(openId);
					if(user==null){
						return "weixin/register/bind";
					}
				}else{
					return "weixin/register/personal";
				}
			}
			return "weixin/service/list";
		}
	}
	
	@RequestMapping("/weixin/service/content")
	public String serviceContent(){
		return "weixin/service/content";
	}
	
	@RequestMapping("/weixin/user")
	public String user(){
		return "weixin/user/userCenter";
	}
	
	@RequestMapping("/weixin/user/service")
	public String userServiceList(){
		return "weixin/user/serviceList";
	}
	
	@RequestMapping("/weixin/user/service/content")
	public String userServiceContent(){
		return "weixin/user/serviceContent";
	}
	
	/**
	 * 通知公告
	 * @return
	 */
	@RequestMapping("/weixin/notice")
	public String notice(){
		return "/weixin/notice/index";
	}
	
	/**
	 * 通知公告详情
	 * @return
	 */
	@RequestMapping("/weixin/notice/content")
	public String noticeContent(String id,HttpServletRequest request){
		request.setAttribute("id", id);
		return "/weixin/notice/content";
	}
	
	/**
	 * 政务服务
	 * @return
	 */
	@RequestMapping("/weixin/govservice")
	public String govservice(){
		String openId = SessionUtils.getOpenId();
		if(StringUtils.isBlank(openId)){
			openId = SessionUtils.refurbishOpenId(RequestUtils.getServletRequest().getParameter("code"));
		}
		return "weixin/govservice/index";
	}
	
	@RequestMapping("/weixin/error")
	public String error(String error){
		RequestUtils.getServletRequest().setAttribute("error", error);
		return "weixin/error/error";
	}
	
	/**
	 * 关注微信时跳转的文章
	 * @return
	 */
	@RequestMapping("/weixin/subscribeShow")
	public String subscribeShow(){
		String index = RequestUtils.getServletRequest().getParameter("index");
		if(StringUtils.equals("1", index)){
			return "weixin/subscribeShow/t1";
		}else if(StringUtils.equals("2", index)){
			return "weixin/subscribeShow/t2";
		}else if(StringUtils.equals("3", index)){
			return "weixin/subscribeShow/t3";
		}
		return null;
	}
	
	/**
	 * 跨域请求数据
	 * @throws IOException 
	 * */
	@RequestMapping(value = "/weixin/ajax")
	@ResponseBody
	public void otherSiteReqData(HttpServletRequest request,HttpServletResponse response,ModelMap model,@RequestParam String param) throws IOException{
		String url = Constant.url;
		String isdecode = request.getParameter("isdecode");
		param = URLEncoder.encode(param, "UTF-8");
		url = url.replace("{param}", param);
		BufferedReader in=null;
		try {
			 StringBuilder json = new StringBuilder();  
			 URL urlObject = new URL(url); 
			 URLConnection uc = urlObject.openConnection();  
			 in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"UTF-8"));  
             String inputLine = null;  
             while ( (inputLine = in.readLine()) != null) {  
                json.append(inputLine);  
             }
             response.setCharacterEncoding("UTF-8"); //设置编码格式  
             response.setContentType("text/json");   //设置数据格式  
             PrintWriter out = response.getWriter(); //获取写入对象  
             String retutnJson = json.toString();
             System.out.println(isdecode);
             if(StringUtils.isNotEmpty(isdecode) && isdecode.equals("true")){
            	 System.out.println("------------------------------------");
            	 retutnJson = retutnJson.replaceAll("%(?![0-9a-fA-F]{2})", "%25");  
            	 retutnJson = URLDecoder.decode(retutnJson, "UTF-8");
            	 System.out.println(retutnJson);
            	 System.out.println("------------------------------------");
             }
             out.print(retutnJson); //将json数据写入流中  
             out.flush();
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			if(in!=null){
				in.close();  
			}
		}
	}
	
	/**
	 * 获取登录用户信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/weixin/loginUser")
	@ResponseBody
	public Object getLoginUser(HttpServletRequest request){
		Map<String,String> user = new HashMap<String,String>();
		user.put("userId", "111111");
		user.put("userName", "LinGe");
		user.put("roleCode", "3");
		user.put("roleName", "中介用户");
		user.put("orgId", "0b01ec1854aae5b40154bed1d1450008");
		request.getSession().setAttribute("loginUser", user);
		Object loginUser = request.getSession().getAttribute("loginUser");
		return loginUser;
	}
	
	/**
	 * 输出响应
	 * 
	 * @param str
	 * @throws IOException
	 */
	protected void write(String str, HttpServletResponse response) throws IOException {
		response.getWriter().write(str);
		response.getWriter().flush();
		response.getWriter().close();
	}
}
